<template>
  <div style="padding: 15px">
    <vxe-toolbar
      id="warehouseLocationId"
      :custom="{ storage: true }"
      export
      :refresh="{ query: findList }"
    >
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="funcAdd">新增</el-button>
        <!-- <el-button @click="upload">导入</el-button>
        <el-button :disabled="printFlag" @click="funcPrint">打印领用单</el-button> -->
      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :export-config='{type:"csv"}'
      :align="allAlign"
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      height="700"
      :loading="loading"
      :data="tableData"
      :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }"
      sort-config.remote
      @sort-change="sortList"
      auto-resize
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="status"
          title="状态"
          min-width="140"
          sortable
          show-header-overflow
          show-overflow
          :formatter="formatterStatus"
        />
        <template v-slot:header="{ column }">
          <el-select
            v-model="listQuery.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in statusList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="code"
          title="调拨单号"
          min-width="200"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.code"
            placeholder="请输入调拨单号"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="shipmentName"
          title="入驻商"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.shipmentName"
            placeholder="请输入入驻商"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="sourceWarehouseName" title="调出仓库" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.sourceWarehouseName"
            placeholder="请输入调出仓库"
            clearable
          />
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="targetWarehouseName" title="调入仓库" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.targetWarehouseName"
            placeholder="请输入调入仓库"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="allocationUnitQuantity"
          title="调拨数量"
          min-width="180"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.allocationUnitQuantityFloor"
              placeholder="下限"
              type='number'
              clearable
              ref="quantity"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.allocationUnitQuantityCeiling"
              placeholder="上限"
              type='number'
              clearable
            />
          </el-row>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="outboundUnitQuantity"
          title="出库数量"
          min-width="180"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.outboundUnitQuantityFloor"
              placeholder="下限"
              type='number'
              clearable
              ref="quantity"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.outboundUnitQuantityCeiling"
              placeholder="上限"
              type='number'
              clearable
            />
          </el-row>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="inboundUnitQuantity"
          title="入库数量"
          min-width="180"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-row type="flex" align="middle" style="color: #dcdfe6">
            <el-input
              v-model="listQuery.inboundUnitQuantityFloor"
              placeholder="下限"
              type='number'
              clearable
              ref="actual"
            />
            &nbsp;-&nbsp;
            <el-input
              v-model="listQuery.inboundUnitQuantityCeiling"
              placeholder="上限"
              type='number'
              clearable
            />
          </el-row>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="verifyName"
          title="审批人"
          min-width="200"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.verifyName"
            placeholder="请输入审批人"
            clearable
          />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="gmtVerify"
          title="审批时间"
          min-width="400"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtVerifyRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtVerify')"
          />
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column
          field="createdName"
          title="创建人"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.createdName"
            placeholder="请输入创建人"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          title="创建时间"
          min-width="400"
          sortable
          show-header-overflow
          show-overflow
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="modifiedName"
          title="修改人"
          min-width="150"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-input
            v-model="listQuery.modifiedName"
            placeholder="请输入修改人"
            clearable
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          title="修改时间"
          min-width="400"
          sortable
        />
        <template v-slot:header="{ column }">
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="(value) => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip

            effect="dark"
            content="修改"
            placement="top"
            v-if="scope.row.status == '0' || scope.row.status == '3'"
          >
            <vxe-button type="text" @click="funcEdit(scope.row.code)">
              <i class="el-icon-edit" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip

            effect="dark"
            content="作废"
            placement="top"
            v-if="scope.row.status == '0' || scope.row.status == '3'"
          >
            <vxe-button type="text" @click="funcInvalid(scope.row.code)">
              <i class="el-icon-document-delete" />
            </vxe-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="查看" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total',
      ]"
      @page-change="handlePageChange"
    />
    <vxe-modal
      v-model="modelCheckFlag"
      title="审核"
      width="600"
      height="500"
      resize
    >
      <compCheck
        ref="checkRef"
        @fatherCheckMethod="fatherCheck"
        @fatherCancelMethod="fatherCancel"
      />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import compCheck from "./components/allocationCheck.vue";
import { allocationList, allocationBlank } from "@/api/store";

export default {
  name: "调拨管理",
  components: {
    compCheck,
  },
  data() {
    return {
      message: "",
      // 日期选项
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      statusList: [
        //状态
        { code: "0", name: "新增" },
        { code: "1", name: "待审核" },
        { code: "2", name: "审核通过" },
        { code: "3", name: "审核不通过" },
        { code: "4", name: "作废" },
      ],
      warehouseData: [],
      shipmentData: [],
      typeList: [],
      dictType: "allocationType",
      loading: false,
      allAlign: "center",
      tableData: [],
      modelCheckFlag: false,
      modelPrintFlag: false,
      modelUploadFlag: false,
      initFinishFlag: false,
      copy: false,
      gmtApprovedRange: "",
      gmtCreatedRange: "",
      gmtVerifyRange:'',
      gmtModifiedRange: "",
      listQuery: {
        total: 0, //总数
        createdBy: "", //创建人
        modifiedBy: "", //修改人
        shipmentName:'',
        code: "", //收货单号 ,
        remarks: "", //备注 ,
        shipmentCode: "", //入驻商 ,
        status: "", //状态 ,
        totalQuantity: "", //订货数量 ,
        type: "", //单据类型 ,
        warehouseCode: "", //仓库
        allocationBy: "",
        targetWarehouseCode:'',
        verifyName:'',
        sourceWarehouseCode:'',
        actualQuantity: "",
        gmtVerify:'',
        approvedBy: "",
        pageNum: 1,
        pageSize: 10,
        sortField: "",
        sortType: "",
        totalQuantityFloor: "", //总数量
        totalQuantityCeiling: "",
        totalActualQuantityFloor: "", //实际领取数量
        totalActualQuantityCeiling: "",
        totalUnitQuantityFloor: "", //总数量
        totalUnitQuantityCeiling: "",
        totalActualUnitQuantityFloor: "", //实际领取数量
        totalActualUnitQuantityCeiling: "",
        allocationUnitQuantity:"",
        allocationUnitQuantityFloor:'',
        allocationUnitQuantityCeiling:'',
        outboundUnitQuantity:"",
        outboundUnitQuantityFloor:'',
        outboundUnitQuantityCeiling:'',
        inboundUnitQuantity:"",
        inboundUnitQuantityFloor:'',
        inboundUnitQuantityCeiling:'',

      },
    };
  },
  created() {
    this.findList()
    this.$eventBus.$on("refreshList", () => {
      this.findList()
    })
  },
  methods: {
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },
    // 翻译入驻商
    formatterShipment({ cellValue }) {
      const sd = this.shipmentData.find((i) => i.code === cellValue);
      return sd ? sd.name : "";
    },
    // 翻译仓库
    formatterWarehouse({ cellValue }) {
      const sd = this.warehouseData.find((i) => i.code === cellValue);
      console.info(sd ? sd.name : "");
      return sd ? sd.name : "";
    },
    // 打印
    funcPrint() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      // if (selectRecords.length > 1) {
      //   return false;
      // }
      let nowDate = new Date();
      let year = nowDate.getFullYear();
      let month = nowDate.getMonth() + 1;
      let date = nowDate.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (date >= 0 && date <= 9) {
        date = "0" + date;
      }
      let systemDate = year + "-" + month + "-" + date;
      this.$refs.printRef.printDate = systemDate;
      this.$refs.printRef.warehouseData = this.warehouseData;
      this.$refs.printRef.typeList = this.typeList;
      let arr = [];
      selectRecords.forEach((i) => {
        arr.push(i.code);
      });
      this.$refs.printRef.getInfo(arr);
      this.modelPrintFlag = true;
    },
    // 单据类型字典查询
    getDictList(dictType) {
      getDictList(dictType).then((response) => {
        this.typeList = response.data[0].dictList;
        this.findList();
        this.initFinishFlag = true;
      });
    },
    // 翻译单据类型
    formatterType({ cellValue }) {
      const sd = this.typeList.find((i) => i.code === cellValue);
      return sd ? sd.name : "";
    },
    // 翻译状态
    formatterStatus({ cellValue }) {
      if (cellValue === "0") {
        return "新增";
      }
      if (cellValue === "1") {
        return "待审核";
      }
      if (cellValue === "2") {
        return "审核通过";
      }
      if (cellValue === "3") {
        return "审核不通过";
      }
      if (cellValue === "4") {
        return "作废";
      }
    },
    //获取列表
    findList() {
      if (
        // 总数量拦截
        this.listQuery.totalQuantityCeiling &&
        Number(this.listQuery.totalQuantityFloor) >
          Number(this.listQuery.totalQuantityCeiling)
      ) {
        this.$message.error("查询总数量下限不得大于上限！");
        this.$refs.quantity.focus();
        return;
      }
      if (
        // 实际领取数量拦截
        this.listQuery.actualQuantityCeiling &&
        Number(this.listQuery.actualQuantityFloor) >
          Number(this.listQuery.actualQuantityCeiling)
      ) {
        this.$message.error("查询实际报损数量下限不得大于上限！");
        this.$refs.actual.focus();
        return;
      }
      this.loading = true;
      return allocationList(this.listQuery).then((response) => {
        this.tableData = response.data.records;
        this.listQuery.total = response.data.total;
        this.loading = false;
      });
    },
    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.listQuery.sortField = property;
        this.listQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findList();
    },
    // 添加方法
    funcAdd() {
      this.$router.push({
        path: "/kngl/allocationAdd",
      });
    },
    // 编辑
    funcEdit(code) {
      this.$router.push({
        path: "/kngl/allocationEdit",
        query: { code: code },
      });
    },
    // 详情方法
    funcDetail(code) {
      this.$router.push({
        path: "/kngl/allocationDetail",
        query: { code: code },
      });
    },
    // 作废方法
    funcInvalid(row) {
      this.$confirm("确认作废吗？")
        .then((_) => {
          allocationBlank(row).then((response) => {
            this.$message({ message: response.msg, type: "success" });
            this.findList();
          });
        })
        .catch((_) => {});
    },
    // 审核
    funcCheck(code) {
      this.$refs.checkRef.getInfo(code);
      this.modelCheckFlag = true;
    },
    // 打印组件的父方法
    fatherPrint() {
      this.modelPrintFlag = false;
      this.findList();
    },
    // 审核组件的父方法
    fatherCheck() {
      this.modelCheckFlag = false;
      this.findList();
    },
    upload() {
      this.modelUploadFlag = true;
    },
    // 增加组件的父方法
    fatherUpload() {
      this.modelUploadFlag = false;
      this.findList();
    },
    // 公共取消
    fatherCancel(modelFlag) {
      switch (modelFlag) {
        case "check":
          this.modelCheckFlag = false;
          break;
        default:
      }
    },
    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.listQuery.pageNum = currentPage;
      this.listQuery.pageSize = pageSize;
      this.findList();
    },
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return "合计";
          }
          if (["pageviews", "forecast"].includes(column.property)) {
            return XEUtils.sum(data, column.property);
          }
          return null;
        }),
      ];
    },
  },
  computed: {
    printFlag: function () {
      if (this.initFinishFlag) {
        let selectRecords = this.$refs.xTable.getCheckboxRecords();
        if (selectRecords.length > 0) {
          return false;
        } else {
          return true;
        }
      }
      return true;
    },
  },
  destroyed() {
    this.$eventBus.$off('refreshList')
  },
};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
